#! /usr/bin/env python 
#coding=utf-8

import wx,time
import sys,os
import tg,jz,yl
from xml.dom import minidom
from head import *

reload(sys)
sys.setdefaultencoding('utf8')

FRAME_W = 400
FRAME_H = 300

BUTTON_W = 60
BUTTON_H = 25

#the bg color
#backcolourR = 210
#backcolourG = 210
#backcolourB = 210

backcolourR = 100
backcolourG = 210
backcolourB = 100

# File Menu Selections
ID_SAVE     = 101
ID_LOAD     = 102
ID_CMDFILE  = 103
ID_TESTCASE = 104
ID_EXIT     = 109
ID_ABOUT    = 110

BMS_DIR = 'bms'
DIR = {'lb1':'LB1','lb2':'LB2','tg':'TG','yl':'YL'}

class MyFrame(wx.Frame):
    def __init__(self, parent):
        wx.Frame.__init__(self, parent, wx.ID_ANY, 'Xml-Creator', size=(FRAME_W,FRAME_H))
        self.SetPosition((wx.DisplaySize()[0]/2 -FRAME_W/2,wx.DisplaySize()[1]/2 - FRAME_H/2))
        self.SetMaxSize(wx.Size(FRAME_W, FRAME_H))
        self.SetMinSize(wx.Size(FRAME_W, FRAME_H))
        self.CreateLayout()
        self.DoLayout()
        self.BindEVT()
        self.curMode = self.playmodeoptions[0]
        self.CreateDIR()
        #合并xml用
        self.dic = {}   
        
    def CreateDIR(self):
        for k in DIR.keys():
            if not os.path.isdir(DIR.get(k)):
                os.mkdir(DIR.get(k))

    def CreateLayout(self):
        myfont = wx.Font(10, wx.NORMAL, wx.ITALIC, wx.BOLD)
        self.Lplaymode = wx.StaticText(self, -1, u'玩法:')
        self.Lplaymode.SetFont(myfont)
        self.playmodeoptions = [u'新炫舞1',u'新炫舞2',u'太鼓',u'音浪']
        self.PlayMode = wx.ComboBox(self, choices=self.playmodeoptions, style = wx.CB_READONLY|wx.CB_DROPDOWN)
        self.PlayMode.SetSelection(0)
        self.StartButton = wx.Button(self, label=u'生成XML')
        self.Collect = wx.Button(self, label=u'合并XML')

    def DoLayout(self):
        self.Lplaymode.SetDimensions(x = 100, y=70,width=50,height=22)
        self.PlayMode.SetDimensions(x = 155, y=70,width=80,height=20)
        self.StartButton.SetDimensions(x=155,y=110,width=80,height=BUTTON_H)
        self.Collect.SetDimensions(x=155,y=150,width=80,height=BUTTON_H)
        
    def BindEVT(self):
        self.PlayMode.Bind(wx.EVT_COMBOBOX, self.OnChange)
        self.StartButton.Bind(wx.EVT_BUTTON, self.OnPress)
        self.Collect.Bind(wx.EVT_BUTTON, self.OnCollect)

    def OnCollect(self,e):
        if self.curMode == u'新炫舞1' or self.curMode == u'新炫舞2':
            self.CollectJZ()
        elif self.curMode == u'太鼓':
            self.CollectTGYL()
        elif self.curMode == u'音浪':
            self.CollectTGYL()
    
    def OnChange(self,e):
        self.curMode = self.PlayMode.GetValue().strip()
        
    def OnPress(self,e):

        if not os.path.isdir(BMS_DIR):
            wx.MessageBox('Not find bms folder','Error',wx.OK)
            return

        os.chdir(BMS_DIR)
        for item in os.listdir('.'):
            if self.curMode == u'新炫舞1':
                if item[0] != '1':
                    pass
                else:
                    jz.SaveJzXML(item)
            elif self.curMode == u'新炫舞2':
                if item[0] != '2':
                    pass
                else:
                    jz.SaveJzXML(item)
            elif self.curMode == u'太鼓':
                if item[0] != '3':
                    pass
                else:
                    tg.SaveTG(item)
            elif self.curMode == u'音浪':
                if item[0] != '4':
                    pass
                else:
                    yl.SaveYL(item)
            else:
                wx.MessageBox(u'不支持该种玩法','Info',wx.OK)
                return
        os.chdir('..')
        wx.MessageBox('Create XML finish','Info',wx.OK)
        return

    def CollectJZ(self):
        if self.curMode == u'新炫舞1' and os.path.isdir('LB1'):
            os.chdir('LB1')
            xmlname = 'DMZ.xml'
        elif self.curMode == u'新炫舞2' and os.path.isdir('LB2'):
            os.chdir('LB2')
            xmlname = 'DOD.xml'
        else:
            return

        for item in os.listdir('.'):
            singlejz = self.LoadJz(item)
            self.dic[singlejz.id] = singlejz

        os.chdir('..')
        self.SaveAllJz(xmlname)

    def SaveAllJz(self,xmlname):

        doc = Document()
        root = doc.createElement('musics')
        doc.appendChild(root)
        
        for k in self.dic.keys():
            obj = self.dic[k]
            music = doc.createElement('music')
            music.setAttribute('id',obj.id)
            music.setAttribute('level',obj.level)
            music.setAttribute('roundgap',obj.roundgap)
            root.appendChild(music)

            for i in xrange(len(obj.round)):
                ele = obj.round[i]
                round = doc.createElement('round')
                p = ele.split(',')
                l = len(p)
                if l==1:
                    #空轮
                    ft = p[0]
                    round.setAttribute('type',ft)
                else:
                    #普通轮
                    ft = p[0]
                    rule = p[1]
                    round.setAttribute('type',ft)
                    round.setAttribute('rule',rule)
                music.appendChild(round)

        s = doc.toprettyxml(indent='    ')
        f = open(xmlname,'w')
        f.write(s)
        self.dic.clear()
        f.close()
        wx.MessageBox('Create XML finish','Info',wx.OK)

    def LoadJz(self,name):
        obj = JZ()
        if not os.path.isfile(name):
            return None
        fp = open(name)
        xmldoc = minidom.parse(fp)
        music = xmldoc.getElementsByTagName('music')
        #一个xml里只有一首歌曲
        obj.id = music[0].attributes['id'].value.strip()
        obj.level = music[0].attributes['level'].value.strip()
        obj.roundgap = music[0].attributes['roundgap'].value.strip()

        roundnode = music[0].getElementsByTagName('round')
        for i in xrange(len(roundnode)):
            ft = roundnode[i].attributes['type'].value.strip()
            try:
                rule = roundnode[i].attributes['rule'].value.strip()
            except:
                rule = None

            if not rule:
                #说明是空轮
                obj.round.append(ft)
            else:
                obj.round.append(ft+','+rule)

        fp.close()
        return obj

    def CollectTGYL(self):
        if self.curMode == u'太鼓' and os.path.isdir('TG'):
            os.chdir('TG')
            xmlname = 'taiko.xml'
        elif self.curMode == u'音浪' and os.path.isdir('YL'):
            os.chdir('YL')
            xmlname = 'wave.xml'
        else:
            return

        for item in os.listdir('.'):
            single = self.LoadTGYL(item)
            self.dic[single.id] = single

        os.chdir('..')
        self.SaveTGYL(xmlname)

    def SaveTGYL(self,xmlname):
        doc = Document()
        root = doc.createElement('musics')
        doc.appendChild(root)
        
        for k in self.dic.keys():
            obj = self.dic[k]
            music = doc.createElement('music')
            music.setAttribute('id',obj.id)
            music.setAttribute('level',obj.level)
            music.setAttribute('roundgap',obj.roundgap)
            music.setAttribute('gridcount',obj.gridcount)
            root.appendChild(music)

            for i in xrange(len(obj.round)):
                thisround = obj.round[i]
                round = doc.createElement('round')
                ft = thisround.ft
                round.setAttribute('type',ft)
                if ft=='3':
                    #空轮
                    pass
                else:
                    #普通轮
                    for j in xrange(8):
                        rule = thisround.rule[j]
                        if rule != '' and rule != None:
                            round.setAttribute('rule%d'%(j+1),rule)
                        sound = thisround.sound[j]
                        if sound != '' and sound != None:
                            round.setAttribute('sound%d'%(j+1),sound)
                        
                music.appendChild(round)

        s = doc.toprettyxml(indent='    ', encoding='UTF-8')
        f = open(xmlname,'w')
        f.write(s)
        self.dic.clear()
        f.close()
        wx.MessageBox('Create XML finish','Info',wx.OK)
        
    def LoadTGYL(self,name):
        obj = TGYL()
        if not os.path.isfile(name):
            return None
        fp = open(name)
        xmldoc = minidom.parse(fp)
        music = xmldoc.getElementsByTagName('music')
        #一个xml里只有一首歌曲
        obj.id = music[0].attributes['id'].value.strip()
        obj.level = music[0].attributes['level'].value.strip()
        obj.gridcount = music[0].attributes['gridcount'].value.strip()
        obj.roundgap = music[0].attributes['roundgap'].value.strip()

        roundnode = music[0].getElementsByTagName('round')
        for i in xrange(len(roundnode)):
            thisround = Round()
            thisround.ft = roundnode[i].attributes['type'].value.strip()
            if thisround.ft == '3':
                #空轮
                pass
            else:
                for j in xrange(8):
                    rule = ''
                    try:
                        attrName = 'rule%d'%(j+1)
                        rule = roundnode[i].attributes[attrName].value.strip()
                    except:
                        #未读到就为空
                        pass
                    thisround.rule[j] = rule
                    
                    sound = ''
                    try:
                        attrName = 'sound%d'%(j+1)
                        sound = roundnode[i].attributes[attrName].value.strip()
                    except:
                        #未读到就为空
                        pass
                    thisround.sound[j] = sound
            obj.round.append(thisround)
        fp.close()
        return obj

class Round:
    def __init__(self):
        self.ft = None
        self.rule = {}
        self.sound = {}

#TG,YL共同的类
class TGYL:
    def __init__(self):
        self.id = None
        self.level = None
        self.gridcount = None
        self.roundgap = None
        self.round = []
        
class JZ:
    def __init__(self):
        self.id = None
        self.level = None
        self.roundgap = None
        self.round = []
    
class MyApp(wx.App):
    def OnInit(self):
        self._frame = MyFrame(None)
        self._frame.Show(True)
        self.SetTopWindow(self._frame)
        return True

if __name__ == '__main__':
    app = MyApp()
    app.MainLoop()
